import { useCallback, useEffect, useState } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { Card, Tag, Skeleton, Button, message, Divider } from 'antd';
import {
  ArrowLeftOutlined,
  UserOutlined,
  ClockCircleOutlined,
  TagOutlined,
} from '@ant-design/icons';
import { getArticleById } from '@/api/article';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

interface Article {
  id: number;
  title: string;
  content: string;
  manager_id: number;
  manager_name: string;
  tags: string[];
  category: 'edible' | 'poisonous' | 'medicinal';
  color: string;
  created_time: string;
}
import 'github-markdown-css/github-markdown.css';
import styles from './index.module.less';
import rehypeRaw from 'rehype-raw';

/**
 * 文章详情
 */
const CategoriesItem = () => {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const category = searchParams.get('category');
  const navigate = useNavigate();
  const [article, setArticle] = useState<Article | null>(null);
  const [loading, setLoading] = useState(true);

  // 获取文章详情
  const fetchArticleDetail = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getArticleById(id as string);
      setArticle(res.data);
    } catch (error) {
      message.error('获取文章详情失败');
      console.error('获取文章详情失败:', error);
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    fetchArticleDetail();
  }, [fetchArticleDetail, id]);

  // 获取分类标签颜色
  const getCategoryColor = (category: 'edible' | 'poisonous' | 'medicinal') => {
    switch (category) {
      case 'poisonous':
        return 'red';
      case 'medicinal':
        return 'blue';
      default:
        return 'green';
    }
  };

  // 获取分类名称
  const getCategoryName = (category: 'edible' | 'poisonous' | 'medicinal') => {
    switch (category) {
      case 'poisonous':
        return '有毒类';
      case 'medicinal':
        return '药用类';
      default:
        return '可食用类';
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4">
      <div className="max-w-4xl mx-auto">
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(`/categories?category=${category}`)}
          className="mb-6 hover:text-emerald-600"
        >
          返回列表
        </Button>

        <Card className="shadow-md">
          {loading ? (
            <div className="space-y-4">
              <Skeleton
                active
                avatar
                paragraph={{ rows: 4 }}
              />
            </div>
          ) : article ? (
            <div className="space-y-6">
              {/* 文章标题 */}
              <div className="text-center">
                <h1 className="text-3xl font-bold text-gray-800 mb-4">{article.title}</h1>
                <div className="flex items-center justify-center space-x-6 text-gray-500">
                  <span className="flex items-center">
                    <UserOutlined className="mr-1" />
                    {article.manager_name}
                  </span>
                  <span className="flex items-center">
                    <ClockCircleOutlined className="mr-1" />
                    {new Date(article.created_time).toLocaleDateString()}
                  </span>
                </div>
              </div>

              <Divider />

              {/* 分类和标签 */}
              <div className="flex flex-wrap gap-2 items-center">
                <Tag
                  color={getCategoryColor(article.category)}
                  className="mr-2"
                >
                  {getCategoryName(article.category)}
                </Tag>
                <Tag color="default">{article.color}</Tag>
                {article.tags.map((tag, index) => (
                  <Tag
                    key={index}
                    icon={<TagOutlined />}
                    color="processing"
                  >
                    {tag}
                  </Tag>
                ))}
              </div>

              {/* 文章内容 */}
              <div className="prose max-w-none">
                <div className={`${styles.markdown} text-sm markdown-body leading-[3]`}>
                  {/* markdown 渲染器 */}
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]} // 支持GFM语法
                    rehypePlugins={[rehypeRaw]} // 支持HTML标签
                  >
                    {article.content}
                  </ReactMarkdown>
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center text-gray-500">文章不存在或已被删除</div>
          )}
        </Card>
      </div>
    </div>
  );
};

export default CategoriesItem;
